#include "dialog.h"
#include "ui_dialog.h"
#include <QMessageBox>

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);
    //在这里创建数据库并打开
    create_database();
    //创建数据表
//    create_table();
    query_table();
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::create_database(){
    //添加数据库驱动
    sqldb = QSqlDatabase::addDatabase("QSQLITE");
    //设置数据库名称
    sqldb.setDatabaseName("student.db");

    //判断打开数据库是否成功
    if(sqldb.open()){
        QMessageBox::information(NULL,"正确","恭喜你，数据库打开成功！",QMessageBox::Ok);
    }else{
        QMessageBox::critical(NULL,"错误","数据库打开失败，请重新检测！",QMessageBox::Ok);
    }

}
void Dialog::create_table(){
    QSqlQuery createquery;
    QString strsql=QString("create table student("
                           "id int primary key not null,"
                           "name text not null,"
                           "score real not null)");
    if(createquery.exec(strsql)){
        QMessageBox::information(NULL,"成功","恭喜你，数据表创建成功！",QMessageBox::Ok);
    }else{
        QMessageBox::critical(NULL,"失败","数据表创建失败，请重新检测！",QMessageBox::Ok);
    }


}
void Dialog::query_table(){

    QString query = "SELECT * FROM student";
    QSqlQueryModel *model = new QSqlQueryModel(this);
    model->setQuery(query);
    // 将 model 设置为 table view 的 model
    ui->tableView->setModel(model);
}
void Dialog::insert_table()
{
    QSqlQuery sqlquery;
    int id = ui->lineEdit_ID->text().toInt();
    if(id==0){
        QMessageBox::critical(NULL,"失败","学生的学号不能为0！",QMessageBox::Ok);
        return;
    }
    QString name = ui->lineEdit_NAME->text();
    if(name==""){
        QMessageBox::critical(NULL,"失败","学生的名字不能为空！",QMessageBox::Ok);
        return;
    }

    double score = ui->lineEdit_SCORE->text().toDouble();
    if(score<0|| score>100){
        QMessageBox::critical(NULL,"失败","学生的成绩必须在0~100之间！",QMessageBox::Ok);
        return;
    }

    QString strs=QString("insert into student "
                         "values(%1,'%2',%3)").arg(id).arg(name).arg(score);
    if(sqlquery.exec(strs)){
        QMessageBox::information(NULL,"成功","恭喜你，数据插入成功！",QMessageBox::Ok);
    }else{
        QMessageBox::critical(NULL,"失败","数据插入失败，请重新检测！",QMessageBox::Ok);
    }
}
void Dialog::update_table(){}
void Dialog::delete_table(){}


void Dialog::on_pushButton_OK_clicked()
{

}

void Dialog::on_pushButton_INSERT_clicked()
{
    insert_table();
    query_table();
    ui->lineEdit_ID->clear();
    ui->lineEdit_NAME->clear();
    ui->lineEdit_SCORE->clear();
}

void Dialog::on_pushButton_UPDATE_clicked()
{

}

void Dialog::on_pushButton_DELETE_clicked()
{

}

void Dialog::on_pushButton_QUERY_clicked()
{

}
